<template>
  <el-dialog
    :visible="isShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="!isShow"
    :before-close="handleClose"
    lock-scroll
    :title="title"
    custom-class="crud-dialog small"
  >
    <div class="flex-1 auto dialog-content">
    <avue-form ref="form" v-model="form" :option="option" @submit="submit">
    </avue-form>
    </div>
    <div class="flex flex-center dialog-footer">
      <el-button type="primary" @click="submitChange">提交</el-button>
      <el-button @click="handleClose">返回</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { option } from "./option";
import {
  getDepartTree,
  getTreeByParentId,
  createDepart,
  editDepart,
} from "@/api/department";
export default {
  name: "AddForm",
  data() {
    return {
      isShow: false,
      title: "",
      form: {
        id: "",
        parentId: "",
        name: "",
      },
      treeData: [],
    };
  },
  computed: {
    option() {
      return option.call(this);
    },
  },
  methods: {
    initForm() {
      this.form = {
        id: "",
        parentId: "",
        name: "",
      };
    },
    getTreeList() {
      getDepartTree().then((res) => {
        if (res.code == 200) {
          this.treeData = (res.result || []).map(row => {
            if (row.code == 'root') {
              // 提了bug  父级部门放开哦 wc
              // row.disabled = true
            }
            return row;
          });
        }
      });
    },
    open(node) {
      this.title = "新增部门";
      this.getTreeList();
      this.form.parentId = node.data.id;
      this.isShow = true;
    },
    edit(node) {
      console.log(node);
      this.title = "编辑部门";
      this.getTreeList();
      this.form = this.$utils.deepCopy(node.data);
      console.log(this.form.id);
      this.isShow = true;
    },
    submit() {
      this.$refs.form.validate((valid, done, msg) => {
        done()
        if (valid) {
          if (this.form.id) {
            editDepart(this.form).then((res) => {
              this.$message.success("编辑成功");
              this.$emit("ok");
              this.handleClose();
            });
          } else {
            createDepart(this.form).then((res) => {
              this.$message.success("新增成功");
              this.$emit("ok");
              this.handleClose();
            });
          }
        } else {
          return false;
        }
      });
    },
    submitChange(){
      this.$refs.form.submit()
    },
    handleClose() {
      this.initForm();
      this.isShow = false;
    },
  },
};
</script>

<style lang="scss" scoped></style>
